const { Menu, dialog } = require('electron')
const got = require('got')
const fs = require('fs')
const path = require('path')
const randomstring = require('randomstring')
const imageType = require('image-type')

const saveas = (srcURL) => {
  const contextMenu = Menu.buildFromTemplate([
    {
      label: '图片另存为...',
      click: async () => {
        // 保存图片  
        if (srcURL !== '') {
          try {
            const response = await got.get(srcURL)
            const chunk = Buffer.from(response.rawBody)
            try {
              const imgType = imageType(chunk)
              const result = await dialog.showSaveDialog({
                title: '图片另存为',
                defaultPath: path.resolve(__dirname, '../public/upload/' + randomstring.generate(10) + "." + imgType.ext)
              })
              if (result) {
                fs.writeFileSync(result.filePath, chunk)
                dialog.showMessageBox({
                  title: '确认信息',
                  message: '图片存储成功'
                })
              }
            } catch(e) {
              dialog.showMessageBox({
                title: '出错了',
                message: '文件夹无效'
              })
            }
          } catch (e) {
            dialog.showMessageBox({
              title: '出错了',
              message: '此图片请求失败。'
            })
          }
        }
      },
      accelerator: 'CommandOrControl+S'
    }
  ])

  contextMenu.popup()
}

module.exports = saveas